import React, { Component } from 'react';
import QueueAnim from 'rc-queue-anim';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import { List, Checkbox, Button, Modal, Bubble, Tools } from 'weaver-mobile';
import { RouteLayout, Form } from 'weaver-mobile-page';
import PersonList from './PersonList';

const getLabel = Tools.getLabel;
const CheckboxItem = Checkbox.CheckboxItem;
const datas = [
    { value: 'message', label: getLabel('383607','消息中心提醒'), checked: 1 },
    { value: 'email', label: getLabel('18845','邮件提醒'), checked: 0 },
    { value: 'sms', label: getLabel('17586','短信提醒'), checked: 0 },
]

@withRouter
@inject('resultStore')
@observer
export default class Urgent extends Component {
    constructor(props) {
        super(props)
        this.prefixCls = 'voting-result-urgent';
        this.path = props.location.pathname;
        this.title = props.location.state && props.location.state.title;
        this.contentKey = null;
        this.state = {
            datas,
        }
    }

    componentWillUnmount() {
        this.currentModal && typeof this.currentModal.close === 'function' && this.currentModal.close();
        this.props.resultStore.urgentStore.clear();
    }
    
    render() {
        const { datas } = this.state;
        const { resultStore } = this.props;
        const { urgentPerLaout, votingid } = resultStore;
        return (
            <div className={this.prefixCls}>
                <List className={`${this.prefixCls}-list`}>
                    {
                        datas && datas.map(data => (
                            <CheckboxItem
                                className={`${this.prefixCls}-line-item`}
                                key={data.value} 
                                checked={data.checked} 
                                onChange={() => this.onChange(data.value)}
                            >
                                <div>{ data.label }</div>
                                <div 
                                    className={`${this.prefixCls}-line-item-setContent`} 
                                    onClick={(e) => this.toContent(e, data.value)}
                                >{getLabel('384894','提醒内容设置')}</div>
                            </CheckboxItem>
                        ))
                    }
                </List>
                <div className={`${this.prefixCls}-btns`}>
                    <Button type='primary' onClick={this.onSubmit}>{getLabel('725','提交')}</Button>
                </div>
                <Route
                    key={this.contentKey}
                    path={`${this.path}/${this.contentKey}Content`}
                    render={() => (
                        <RouteLayout>
                            <div key={this.contentKey} className="wm-route-layout">
                                <RemindContent contentKey={this.contentKey} voteName={this.title} votingid={votingid}/>
                            </div>
                        </RouteLayout>
                    )}
                />
                <Route
                    key={urgentPerLaout.id}
                    path={urgentPerLaout.path}
                    render={() => (
                        <RouteLayout>
                            <div key={this.contentKey} className="wm-route-layout">
                                <PersonList />
                            </div>
                        </RouteLayout>
                    )}
                />
            </div>
        )
    }
    
    toContent = (e, value) => {
        const { history } = this.props;
        e.preventDefault();
        e.stopPropagation()
        this.contentKey = value;
        history.push({pathname: `${this.path}/${value}Content`});
    }

    onChange = (key) => {
        let datas_temp = this.state.datas;
        datas_temp = datas_temp.map(data => {
            if (key === data.value) {
                data = {...data, checked: !data.checked}
            }
            return data
        })
        this.setState({datas: datas_temp})
    }

    onSubmit = () => {
        const { resultStore: { urgentStore, votingid } } = this.props;
        const { getUrgentNum } = urgentStore;
        let selectValue = this.state.datas.filter(v => v.checked).map(v => v.value);
        if (selectValue.length === 0) {
            this.currentModal = Modal.alert(getLabel('83130','至少选择一种提醒方式'), '', [
                { text: getLabel('826','确定') }
            ])
            return
        }
        getUrgentNum({votingid}).then(res => {
            if (res.num * 1) {
                this.currentModal = Modal.alert(
                    <div>
                        {getLabel('516644','确定给未填写调查的')}
                        <span /* style={{color: 'red'}} */ onClick={() => {
                            // this.currentModal && typeof this.currentModal.close === 'function' && this.currentModal.close();
                            // history.push({pathname: `${this.path}/resnotJoin`, state: {id: votingid}})
                        }}>{res.num}</span> {getLabel('516645','位参与者发送催办提醒？') }
                    </div>, '', [
                    { text: getLabel('31129','取消') },
                    { text: getLabel('826','确定'), onPress: () => this.onOk(selectValue) }
                ])
            } else {
                this.currentModal = Modal.alert(getLabel('516746','调查已全部填写，无须进行催办'), '', [
                    { text: getLabel('826','确定') }
                ])
            }
        })
    }

    onOk = (selectValue) => {
        const { history, resultStore: { urgentStore, votingid } } = this.props;
        let { content, initContent, urgent } = urgentStore;
       
        new Promise((resolve) => {
            if (!content) {
                content = initContent(this.title);
                resolve();
            } else {
                resolve();
            }
        }).then(() => {
            let params = {
                votingid,
                remindType: selectValue.join(),
                ...toJS(content)
            }
            urgent(params).then(res => {
                if (res.status === '1') {
                    history.go(-1)
                    Bubble.success(getLabel('385379','催办成功！'));
                } else {
                    Bubble.error(getLabel('384402','操作失败，请重试！'))
                }
            })
        })
    }
}

@withRouter
@inject('resultStore')
@observer
class RemindContent extends Component {
    constructor(props) {
        super(props)
        this.prefixCls = `voting-result-urgent-content`
    }

    componentDidMount() {
        const { contentKey, voteName, location: { pathname }, resultStore: { urgentStore }, votingid } = this.props;
        const { initialState, setStoreState } = urgentStore;
        initialState(contentKey, pathname, voteName, {votingid: votingid});
        setStoreState({path: pathname, title: voteName});
    }

    renderContent = () => {
        const { contentKey, resultStore: { urgentStore } } = this.props;
        const form = urgentStore[`${contentKey}Form`];
        if (form) {
            return (
                <div className={`${this.prefixCls}-${contentKey}`}>
                    <div className={`${this.prefixCls}-${contentKey}-form`}>
                        <Form store={form} style={{ height: '100%' }}>
                            <QueueAnim style={{overflowX: 'hidden'}}>{this.getFields(form)}</QueueAnim>
                        </Form>
                    </div>
                    <div className={`${this.prefixCls}-${contentKey}-btns`}>
                        <Button type='primary' onClick={this.onSave}>{getLabel('30986','保存')}</Button>
                    </div>
                </div>
            )
        }
    }

    getFields = (form) => {
        const fields = [];
        if (form.isInit) {
            form.conditioninfo.forEach((group) => {
            group.items.forEach((field) => {
                fields.push(<Form.Item
                    key={field.domkey.join('__')}
                    form={form}
                    fieldConfig={field}
                    onChange={(...args) => {            
                        form.onChange.apply(this, args);
                    }}
                />);
            });
          });
        }
        return fields;
    }
    
    render() {
        return (
            <div className={this.prefixCls}>
                { this.renderContent() }
            </div>
        )
    }

    // 保存
    onSave = () => {
        const { contentKey, history, resultStore: { urgentStore } } = this.props;
        const { setStoreState, content } = urgentStore;
        let validResult = urgentStore[`${contentKey}Form`].doValidate();
        if (validResult.pass) {
            let content_temp = content;
            let formParams = urgentStore[`${contentKey}Form`].formParams;
            if (!formParams[`${contentKey}Content`]) {
                Bubble.error(getLabel('516765','请填写提醒内容'));
                return
            }
            content_temp = {
                ...content_temp,
                ...formParams,
            }
            setStoreState({content: content_temp})
            history.go(-1)
        } else {
            Bubble.error(validResult.message);
        }
    }
}